package server.core;

import lombok.Data;
import lombok.SneakyThrows;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.HttpServlet;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class Context {
    private String baseContextPath;
    private TomcatClassLoader classLoader;
    private Map<String, HttpServlet> servletMap = new HashMap<>();

    @SneakyThrows
    public void init(Path path) {
//        classLoader = new TomcatClassLoader();
        classLoader = new TomcatClassLoader(new URL[]{path.toUri().toURL()});
        baseContextPath = "/" + path.getFileName().toString();
        loadServlet(path);
    }

    /**
     * 加载解析web.xml，初始化Servlet
     * @param path
     */
    private void loadServlet(Path path) {
        try (InputStream resourceAsStream = new FileInputStream(Paths.get(path.toString(), "web.xml").toFile())) {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                servletMap.put(urlPattern, (HttpServlet)classLoader.loadClass(servletClass).newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
